package tools

import (
	"bytes"
	"encoding/xml"
	"errors"
	"fmt"
	"math/rand"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

func UrlToHost(str string) (string, error) {
	re := regexp.MustCompile(`^(https?://[^/]+)`)
	match := re.FindStringSubmatch(str)
	if match != nil {
		return match[1] + "/", nil
	} else {
		return "", errors.New("无法获取都域名")
	}
}

func StringRandom(index int, length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(index)])
	}
	return string(result)
}

func StructToXml(data interface{}) (string, error) {
	var buffer bytes.Buffer

	encoder := xml.NewEncoder(&buffer)
	err := encoder.Encode(data)
	if err != nil {
		return "", errors.New(fmt.Sprintf("解析结构错误：%v", err))
	}

	// 获取生成的XML字符串
	return buffer.String(), nil
}

func FilePathToFilename(filePath string) (filename string, ext string) {
	ext = strings.TrimPrefix(filepath.Ext(filePath), ".")
	filename = filepath.Base(filePath)
	return filename, ext
}
